package com.alibaba.citrus.cr.mn.order.center.facade.repository.impl;

import com.alibaba.citrus.cr.mn.order.center.facade.function.dataobject.AtomOrderDO;
import com.alibaba.citrus.cr.mn.order.center.facade.repository.AtomOrderQueryRepository;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.crb2btradecenter.domain.order.dto.QueryByOrderNosRequest;
import com.epoch.app.crb2btradecenter.domain.order.dto.QueryByOrderNosV2Request;
import com.epoch.app.crb2btradecenter.domain.order.model.Order;
import com.epoch.app.crb2btradecenter.domain.order.service.OrderService;
import com.epoch.app.crb2btradecenter.domain.orderline.dto.QueryOrderLineByMainIdListRequest;
import com.epoch.app.crb2btradecenter.domain.orderline.model.OrderLine;
import com.epoch.app.crb2btradecenter.domain.orderline.service.OrderLineService;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author zhangxiaorui
 * @ClassName AtomOrderQueryRepositoryImpl
 * @description: TODO
 * @date 2023/04/27 13:10
 * @version: 1.0
 */
@Component
public class AtomOrderQueryRepositoryImpl implements AtomOrderQueryRepository {
    private static final Log log = Log.getLogger(AtomOrderQueryRepositoryImpl.class);
    @Resource
    private OrderLineService orderLineService;
    @Resource
    private OrderService orderService;

    @Override
    @Deprecated
    public Result<List<AtomOrderDO>> queryByOrderNos(QueryByOrderNosRequest request) {
        log.info("AtomOrderQueryRepositoryImpl#queryByOrderNos request={}", request);
        Result<List<Order>> listResult = orderService.queryByOrderNos(request);
        if (Objects.isNull(listResult) || !listResult.isSuccess() || CollectionUtils.isEmpty(listResult.getResult())) {
            return Result.listSuccess(Lists.newArrayList(), 0);
        }

        return Result.listSuccess(buildResult(listResult.getResult()), listResult.getTotal());
    }

    @Override
    public List<AtomOrderDO> queryBySourceOrderNos(QueryByOrderNosV2Request request) {
        log.info("AtomOrderQueryRepositoryImpl#queryBySourceOrderNos request={}", request);
        Result<List<Order>> listResult = orderService.queryByOrderNosV2(request);
        if (Objects.isNull(listResult) || !listResult.isSuccess() || CollectionUtils.isEmpty(listResult.getResult())) {
            return Lists.newArrayList();
        }

        return buildResult(listResult.getResult());
    }

    @Override
    public List<AtomOrderDO> queryByOrderBizIds(QueryByOrderNosV2Request request, boolean needLines) {
        try {
            request.setStart(0);
            request.setLimit(request.getSalesOrderNo().size());
            log.info("AtomOrderQueryRepositoryImpl#queryByOrderBizIds request={}", request);
            Result<List<Order>> listResult = orderService.queryByOrderNosV2(request);
            if (Objects.isNull(listResult) || !listResult.isSuccess() || CollectionUtils.isEmpty(listResult.getResult())) {
                return Lists.newArrayList();
            }

            return buildResult(listResult.getResult());
        } catch (Exception e) {
            log.error("AtomOrderQueryRepositoryImpl#queryByOrderBizIds error", e);
        }
        return Lists.newArrayList();
    }

    private List<AtomOrderDO> buildResult(List<Order> orderList) {
        Map<Long, List<OrderLine>> orderLineOfMainMap = queryOrderLineMapByMainIdList(orderList);
        return orderList.stream().map(order -> {
            AtomOrderDO atomOrderDO = new AtomOrderDO();
            atomOrderDO.setOrder(order);
            atomOrderDO.setOrderLines(orderLineOfMainMap.get(order.getId()));
            return atomOrderDO;
        }).collect(Collectors.toList());
    }

    @NotNull
    private Map<Long, List<OrderLine>> queryOrderLineMapByMainIdList(List<Order> orderList) {
        List<Long> mainIds = orderList.stream().map(Order::getId).distinct().collect(Collectors.toList());
        QueryOrderLineByMainIdListRequest mainIdListRequest = new QueryOrderLineByMainIdListRequest();
        mainIdListRequest.setMainIdList(mainIds);
        mainIdListRequest.setStart(0);
        mainIdListRequest.setLimit(1000);

        Result<List<OrderLine>> orderLineByMainIdList = orderLineService.queryOrderLineByMainIdList(mainIdListRequest);
        log.info("orderLineByMainIdList结果:{}", JSON.toJSONString(orderLineByMainIdList));
        return Optional.ofNullable(orderLineByMainIdList.getResult())
                .orElse(Lists.newArrayList())
                .stream().collect(Collectors.groupingBy(OrderLine::getMainId));
    }
}
